package it.elis.media.library.dao.springImpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport;

import it.elis.media.library.dao.BookDao;
import it.elis.media.library.model.data.Author;
import it.elis.media.library.model.data.Book;

public class BookDaoSpringImpl extends NamedParameterJdbcDaoSupport implements
		BookDao {

	Logger logger = Logger.getLogger(this.getClass());
	
	private String searchBookBasicQuery = "select  b.prog_book_id, "
			+ "		b.title, " + "		b.isin_code, " + "		b.date_publication, "
			+ "		a.prog_author_id, " + "		a.name, " + "		a.surname "
			+ "from book b, author a "
			+ "where a.prog_author_id = b.prog_author_id ";

	@Override
	public List<Book> search(Book bookCriteria) {
		StringBuilder builder = new StringBuilder();
		
		builder.append(searchBookBasicQuery);
		Map<String, String> parameterMap = new HashMap<String, String>();

		// se e' presente il nome metto il nome
		if (null != bookCriteria.getTitle()) {
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append("%");
			stringBuilder.append(bookCriteria.getTitle().toUpperCase());
			stringBuilder.append("%");
			parameterMap.put("title", stringBuilder.toString());
			builder.append(" and upper(b.title) like :title");
		}

		// Se e' presente l'isinCode uso quello
		if (null != bookCriteria.getIsinCode()) {
			parameterMap.put("isinCode", bookCriteria.getIsinCode());
			builder.append(" and b.isin_code = :isinCode");
		}
		
		logger.info(builder.toString());
		
		return getNamedParameterJdbcTemplate().query(builder.toString(),
				parameterMap, new BookMapper());
	}

}

class BookMapper implements RowMapper<Book> {

	@Override
	public Book mapRow(ResultSet arg0, int arg1) throws SQLException {
		Book book = new Book();
		book.setProgBookId(arg0.getInt("prog_book_id"));
		book.setTitle(arg0.getString("title"));
		book.setIsinCode(arg0.getString("isin_code"));
		book.setDatePublication(arg0.getTimestamp("date_publication"));
		
		Author author = new Author();
		author.setProgAuthorId(arg0.getInt("prog_author_id"));
		author.setName(arg0.getString("name"));
		author.setSurname(arg0.getString("surname"));
		
		book.setAuthor(author);
		return book;
	}

}

